var common = {
	init: function() {
		common.fadeInIcons();
		common.alertsForms();
		common.backTopDataTables();
		common.backgroundTableAprovarTodos();
		common.addAttrInputFiltro();
		common.selectAllChk();
		common.datePickers();
		common.switchery();
		common.iePlaceHolder();
		common.buttonClear();
		common.menuScroll();
		common.anexos();
		common.hideAlert();
		common.limparPesquisa();
		common.populateTooltips();
		common.tooltipDisabled();
		common.stopSounds();
			
	},
	
	//Parar os audios das modais
stopSounds: function() {
	document.addEventListener('play', function(e){
    var audios = document.getElementsByTagName('audio');
    for(var i = 0, len = audios.length; i < len;i++){
        if(audios[i] != e.target){
            audios[i].pause();
        }
    }
}, true);

$(document).on('hidden.bs.modal', function () {
   $('audio').each(function(){
			$(this).trigger('pause');
		});
 })
$(document).on('keyup',function(evt) {
    if (evt.keyCode == 27) {
       $('audio').each(function(){
				$(this).trigger('pause');
		});
	}
});
  
	$('.close, .save, .cancel' , $('.modal-footer').find(':button')).on('click', function(){
		$('audio').each(function(){
			$(this).trigger('pause');
});
	});
},

	inputCustom : function(){
		$(':file').filestyle({buttonText: "Anexar Arquivo"});
	},

	fadeInIcons : function(){
		$('.page-header.row strong').click(function() {
			$('.form-horizontal .ajudaTit').toggle('fast');
		});
	},

	alertsForms : function(){
		$(".encaminhar").click(function(){
			$(".alert.alert-danger").alert().fadeIn('slow');
			$('body, html').animate({scrollTop:0},600);
		});

		$(".gravar").click(function(){
			$(".alert.alert-success").alert().fadeIn('slow');
			$('body, html').animate({scrollTop:0},600);
		});
	},

	backTopDataTables : function(){
		$(".pagination , .btn-recolher, .validar-solicitacao tr td .aprovar-todos").click(function(){
			$('body , html').animate({scrollTop:0},600);
		});
	},

	backgroundTableAprovarTodos : function(){
		$(".validar-solicitacao tr td .aprovar-todos").click(function(){
			$(".validar-solicitacao").css("background-color" , "#E1EED9");
			$(".validar-solicitacao tr:last-child td, .validar-solicitacao tr td .tables-internas tr td").css("background-color" , "#ffffff");
		});
	},

	//Função para add classe e attr no campo filtrar por palavra e chamada dos tooltips nos forms.
	addAttrInputFiltro : function(){
		$('.dataTables_filter').find('.glyphicon').remove();
		$('.dataTables_filter').append('<a href="javascript:;" class="glyphicon glyphicon-info-sign ajuda ajudaTit" data-toggle="tooltip" title="O filtro se aplica apenas para os resultados apresentados.">&nbsp</a>');
		$('.glyphicon-info-sign.ajudaTit').tooltip({ 'placement': 'right', 'trigger': 'hover' });
		$('.dataTables_filter input').attr('placeholder','Filtrar por palavra').addClass('form-control');
		$('a.DTTT_button').addClass(' btn-default btn');
		$('.page-header .ajudaTit').tooltip({ 'placement': 'right', 'trigger': 'hover' });
		//$('.panel-sma .panel-title a').tooltip();
		$('[data-toggle="tooltip"]').tooltip();
	},

	hideAlert : function() {
		$('body').on('click', '[data-hide]', function(){
			$(this).closest("." + $(this).attr("data-hide")).hide();
		});
	},

	comentarios : function(tipo) {
		var alerts = $('.formSMA input[data-alert]');
		for (var i =  alerts.length - 1; i >= 0; i--) {
			$(alerts[i]).attr('title', $(alerts[i]).attr('data-alert') );
			$(alerts[i]).addClass(tipo);
			$('.' + tipo).tooltip({ 'placement': 'bottom'});
			$('body, html').animate({scrollTop:330},600);
			$('.alert-warning').fadeIn();
		}
	},

	messageWarning: function(element,type,message) {
		$(element).html('<div class="alert alert-' +type + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');
		$(element).find('.alert').fadeIn();
	},

	selectAllChk: function(attribute){
		$(".selectall").on('change', function(){
			var status = $(this).is(":checked") ? true : false;
			$(this).parents('table').find('tbody input[type="checkbox"]').prop("checked",status);
		});
	},

	setMasks: function(){
		$('input[type="text"]').setMask();
	},

	datePickers : function(){
		$('.dataPick').daterangepicker({
			startDate: moment().date(1),
			endDate: moment(),
			format: 'DD/MM/YYYY',
			setStartDate: moment(),
			setEndDate: moment()
		});
		
		$(".dataPickUG").datepicker({
        changeMonth: true,
    		changeYear: true,
        showButtonPanel: true,
        dateFormat: "dd/mm/yy",
				yearRange: '-10:+10',
        beforeShow: function (e, t) {
            $(this).datepicker("hide");
            $("#ui-datepicker-div").addClass("hide-calendar");
			$("#ui-datepicker-div").addClass('MonthDatePicker');
			$("#ui-datepicker-div").addClass('HideTodayButton');
        },
		onClose: function(dateText, inst){
			var n = Math.abs($("#ui-datepicker-div .ui-datepicker-month :selected").val());
            var y = Math.abs($("#ui-datepicker-div .ui-datepicker-year :selected").val());
			 $(this).datepicker("setDate", new Date(y, n, 1));
		}
    });

		$(document).find('.dataPickSingle').each(function() {
			if($(this).val() == "") {
				$('.dataPickSingle').daterangepicker({
					singleDatePicker: true,
					startDate: moment(),
					format: 'DD/MM/YYYY',
					setStartDate: moment()});				
			} else {
				$('.dataPickSingle').daterangepicker({
					singleDatePicker: true,
					format: 'DD/MM/YYYY',
					setStartDate: moment()
				});
			}
		});
			
	},	

	//Checkbox Switchery ( IOS Style )
	switchery: function (){
		$(function() {
			var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
			elems.forEach(function(html) {
				var switchery = new Switchery(html);
			});

		});
	},

	iePlaceHolder: function (){
	$(function(){ $('[placeholder]').focus(function(e) {
		 var elemento = $(e.target); 
		 if (elemento.val() == elemento.attr('placeholder')) { elemento.val(''); 
		 } }).blur(function(e) { var elemento = $(e.target); 
		 if (elemento.val() == '' || elemento.val() == elemento.attr('placeholder')) { elemento.val(elemento.attr('placeholder')); 
		 } }).trigger('blur');
		  });

		$(function(){ 
			$('[placeholder]').parents('form').bind('submit', function(e) {
	
		var alertHtml = $('#filtro_empresa').val();

				 	alert(alertHtml);
					 var $form = $(e.target); if(!!$form.data('binded') == false){
						  $(e.target).find('[placeholder]').each(function(i,el) {
								 if (el.val() == el.attr('placeholder')) { el.val(''); 
								
					} 
					});
					
					 $form.data('binded',true); 
					} 
				});
		 });

	},

	/* Função que transforma os labels */
	funcaoLabel : function() {
		$('table').find('.tipo').each(function(){
			var nomeLabel = $(this).text();
			switch(nomeLabel){
				case "Em preenchimento":
				$(this).html('<span class="label label-status">Em preenchimento</span>');
				break;
				case "Pedido Realizado":
				$(this).html('<span class="label label-cancel">Pedido Realizado</span>');
				break;
				case "Autorização do Pagamento":
				$(this).html('<span class="label label-approved">Autorização do Pagamento</span>');
				break;
				case "Em Transporte":
				$(this).html('<span class="label label-status">Em Transporte</span>');
				break;
				case "Cancelada":
				$(this).html('<span class="label label-cancel">Cancelada</span>');
				break;
				case "Concluída":
				$(this).html('<span class="label label-approved">Concluída</span>');
				break;
			}
		});
		$('.indicador .label').tooltip({ 'placement': 'bottom', 'trigger': 'hover' });

	},

	maisInfoAndamento : function() {
		$('#andamentoTable tr').off('click');
		$('#andamentoTable tr').on('click',function () {
			var nTr = this;
			var tipoExt = $(this).find('.tipo').text();

			if ( oTable.fnIsOpen(nTr) ) {
				oTable.fnClose( nTr );
			} else {
				common.chamarDetalheLinha(nTr, oTable);
			}
		});
	},

	maisInfoJuridico : function() {
		$('#juridicoTable tr').off('click');
		$('#juridicoTable tr').on('click',function () {
			var nTr = this;
			var tipoExt = $(this).find('.tipo').text();

			if ( oTable.fnIsOpen(nTr) ) {
				oTable.fnClose( nTr );
			} else {
				common.chamarDetalheLinha(nTr, oTable);
			}
		});
	},

	maisInfoFinal : function() {
		$('#finalizadaTable tr').off('click');
		$('#finalizadaTable tr').on('click',function () {

			var nTr = this;
			var tipoExtB = $(this).find('.tipo').text();

			if ( oTableB.fnIsOpen(nTr) ) {
				oTableB.fnClose( nTr );
			} else {
				common.chamarDetalheLinha(nTr, oTableB);
			}
		});
	},

	chamarDetalheLinha : function(elemento, datatablesObject){

		var tipoExt = $(elemento).find('.tipo').text();
		var idDiv = $(elemento.children[0]).text();
		var status = $(elemento).find('td').eq(2).text().toLowerCase();

		switch(tipoExt){
			case "Em preenchimento":
			datatablesObject.fnOpen( elemento, preenchimento( elemento ), 'details' );
			break;
			case "Pedido Realizado":
			datatablesObject.fnOpen( elemento, pedidoRealizado( elemento ), 'details' );
			break;
			case "Autorização do Pagamento":
			datatablesObject.fnOpen( elemento, autorizacaoPagamento( elemento ), 'details' );
			break;
			case "Em Transporte":
			datatablesObject.fnOpen( elemento, emTransporte( elemento ), 'details' );
			break;
			case "Cancelada":
			datatablesObject.fnOpen( elemento, cancelada ( elemento ), 'details' );
			break;
			case "Concluída":
			datatablesObject.fnOpen( elemento, concluida ( elemento, status ), 'details' );
			break;
		}

		$('[data-toggle="tooltip"]').tooltip();
	},
	tooltips : function(animate) {
		$('.error').tooltip('destroy');
		var errors = $('.formSMA *[data-error]');
		for (var i =  errors.length - 1; i >= 0; i--) {
			$(errors[i]).attr('title', $(errors[i]).attr('data-error') );
			$(errors[i]).addClass('error');
		}
		if (animate) {
			$('body, html').animate({scrollTop:330},600);
			$('.alert-danger').fadeIn();
		}
		$('.error').tooltip({ 'placement': 'right'});
	},
	buttonClear : function() {
		$('body').on('click','.btn-clear', function(event) {
			event.preventDefault();
			$($(this).data('clear')).val('');
		});
	},

	menuScroll : function() {
		if ($('#sma_status').size() > 0) {
			$(window).scroll(function () {
				if ( $(this).scrollTop() > 400 && !$('#sma_status').hasClass('navbar-fixed-top') ) {
					$('.menu-acoes').hide().addClass('fixed');
					$('#sma_status').addClass('navbar-fixed-top').animate({top: 55},500, function(){
						$('.menu-acoes').fadeIn();
					});


				} else if ( $(this).scrollTop() <= 400 ) {
					$('#sma_status').css('top',0).removeClass('navbar-fixed-top');
					$('.menu-acoes').removeClass('fixed');
				}
			});
		}
	},

	getObjects : function(obj, key, val) {
		var objects = [];
		for (var i in obj) {
			if (!obj.hasOwnProperty(i)) continue;
			if (typeof obj[i] == 'object') {
				objects = objects.concat(getObjects(obj[i], key, val));
			} else if (i == key && obj[key] == val) {
				objects.push(obj);
			}
		}
		return objects;
	},

	anexos : function() {
		$('.form-group').on('click', '.anexoLink', function(event) {
			modalAnexoTitulo = $(this).parents('.form-group').find('label').text();
		});

		$('.panel').on('click', '.anexoLink', function(event) {
			modalAnexoTitulo = $(this).parents('.panel').find('.panel-title').text();
		});

		$('#modal-anexar-documentos').on('shown.bs.modal', function (e) {
			$('#modal-anexar-documentos').find('.modal-title').text( modalAnexoTitulo );
		});
	},

	// Função que faz funcionar o tooltip em campos como readonly
	tooltipDisabled : function(){
		$.each($('[disabled=disabled]'), function(index, value) { 
			if($(this).has('data-error')){
				var text = $(this).attr('data-error');
				$(this).parent().attr('data-original-title',text).attr('data-toggle','tooltip');
				$('[data-toggle="tooltip"]').tooltip({ placement:'right'});
				if ($(this).is('select')) {
					$(this).parent().append("<iframe style='position: absolute; top: 0; left: 0; height: 100%; width:100%; border: 0;'></iframe>");
				}
			}
		});
	},
	// Função de apoio á tooltipDisabled para colorir o tooltip, ela deve ser chamada no botão de verificar inconsistência
	tooltipErrorDisabled : function(){
		$.each($('[disabled=disabled]'), function(index, value) { 
			$(this).parent().parent().addClass('data-error');
		});
	},
	//Função para desativar o tooltipDisabled. Usada quando for "ativar" o campo. Forma de usar:
	//common.tooltipErrorEnabled($.find('input[disabled=disabled]'));
	tooltipErrorEnabled : function(campos){
		$.each(campos, function(index, item) {
			$(item).parent().removeAttr('data-original-title').removeAttr('data-toggle','tooltip');
			$(item).parent().find('iframe').remove();
		});
	},
	

	populateTooltips: function () {

	    var campos = $('label[data-msg] , span[data-msg] , a[data-msg]');

	    var _tooltips;
	    // Para funcionar no mockup//$.get('js/tooltips.htm', function(data){

	    $.get('recursos/js/tooltips.htm', function (data) {

	        _tooltips = jQuery.parseJSON(data).tooltips;

	        for (var i = 0; i < campos.length; i++) {

	        	alert($(campos[i]).data('msg'));
	        	
	            if (_tooltips[$(campos[i]).data('msg')]) {
	            	
	                $(campos[i]).attr('data-original-title', _tooltips[$(campos[i]).data('msg')].msg).attr('data-toggle', 'tooltip');

	            }

	        }

	        $('label[data-toggle="tooltip"]').tooltip();

	    });

	},

	loader : {
		show : function(element) {
			if ($(element).find('.overlay').length == 1) {
				return;
			}
			oldPosition = $(element).css('position');
			$(element).css('position','relative');
			$('<div class="overlay"><div class="wrapper"><div class="loader"></div><div class="bg"></div></div></div>').appendTo(element);
			if (element === 'body') {
				$(element).find('.overlay').width( $(window).outerWidth() ).height( $(window).height() ).css('top', $(window).scrollTop() );
				$(element).find('.overlay .loader').css('top','50%');
				$('html, body').on('mousewheel', function(event) {
					event.preventDefault();
					return false;
				});
			} else {
				$(element).find('.overlay').width( $(element).outerWidth() ).height( $(element).outerHeight() );
			}
			$(element).find('.overlay').fadeIn();
		},

		hide : function(element) {
			if ($(element).find('.overlay').length === 0) {
				return;
			}
			$(element).find('.overlay').fadeOut(function(){
				$(element).find('.overlay').remove();
			});
			$(element).css('position',oldPosition);
			if (element === 'body') {
						//$('html, body').css('overflow','visible');
						$('html, body').off('mousewheel');
					}

		},

		destroy : function() {
			$('.overlay').fadeOut(function(){
				$('.overlay').remove();
			});
			$(element).css('position',oldPosition);
			if (element === 'body') {
				$('html, body').css('overflow','visible');
				$('html, body').off('mousewheel');
			}
		}
	},

	limparPesquisa: function() {

		// Coloca os inputs como readonly
		$( "div.panel-heading input[id][type$='text']" ).each(function() {
			$(this).prop('readonly', 'readonly');
		});

		//reset nos icones de lixeira
		$('.panel-heading').find('.reset-hide').hide();

		$('div.panel-heading').each(function() {
			if($(this).find(':input').val() === "") {
				$(this).find('.reset-hide').hide();
			} else {
				$(this).find('.reset-hide').show();
			}

			$('.panel-heading').find('.panel-title').on('click', '.input-group-addon, input', function(){
				$(this).parents('.panel-title').find('[data-toggle="collapse"]').click();
			});

			$(this).find('.panel-title').find(':input').prop('readonly', 'readonly');
			$(this).on('click', '.reset-hide', function(){
				$(this).parents('.panel-heading').find(':input').val("");
				$(this).hide();
			});
		});

		$('.panel-heading').find('.panel-title').on('click', '.input-group-addon, input', function(){
			$(this)[0].parent().find('a').click();
			return false
		});
	}
};

var sSwfPath = "recursos/js/swf/copy_csv_xls_pdf.swf";

var aoLanguage = {
	"sProcessing":   "Processando...",
	"sLengthMenu":   "Quantidade de resultados: _MENU_",
	"sZeroRecords":  "Não foram encontrados resultados",
	"sInfo":         "Mostrando de _START_ até _END_ de _TOTAL_ registros",
	"sInfoEmpty":    "Mostrando de 0 até 0 de 0 registros",
	"sInfoFiltered": "(filtrado de _MAX_ registros no total)",
	"sInfoPostFix":  "",
	"sSearch":       "",
	"sUrl":          "",
	"oPaginate": {
		"sFirst":    "Primeiro",
		"sPrevious": "Anterior",
		"sNext":     "Seguinte",
		"sLast":     "Último"
	}
};

/**
 * Transforma caracteres escape em caracteres privados do jquery.
 * Ex: "endereco.cep.numero" -> "endereco\.cep\.numero"
 */
function jqEscapeCaracteres(nome) {
    return nome.replace( /(:|\.|\[|\]|,)/g, "\\$1" );
}


/* BACKSPACE - não voltar */

$(document).keydown(function(e) {
var element = e.target.nodeName.toLowerCase();
if (element != 'input' && element != 'textarea') {
    if (e.keyCode === 8) {
        return false;
    }
}
});


/* ENTER */
$(document).ready(function() {
	$('input').on("keypress", function(e) {
		var me = $(this);
			var father = $(this).parent().parent().parent();
				if (e.keyCode == 13) {
				//alert("Enter pressed");
				if(father.hasClass('panel-body')){
				$(this).parent().parent().find('button').click()
			}
			return false; // prevent the button click from happening
		}
	});
});

$(function() {
	common.init();
});